import React, { useState } from 'react';
import {
  type Layout,
  type Layouts,
  Responsive,
  WidthProvider,
} from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

// 包装响应式组件
const ResponsiveGridLayout = WidthProvider(Responsive);

// 网格项属性接口
interface GridItemProps {
  i: string;
  title: string;
  color: string;
}

const DraggableGrid: React.FC = () => {
  // 初始化布局状态
  const [layouts, setLayouts] = useState<Layouts>({
    lg: [
      { i: '1', x: 0, y: 0, w: 2, h: 2 },
      { i: '2', x: 0, y: 0, w: 2, h: 2 },
      { i: '3', x: 0, y: 0, w: 2, h: 2 },
      { i: '4', x: 0, y: 0, w: 2, h: 2 },
      { i: '5', x: 0, y: 0, w: 4, h: 2 },
    ],
    md: [
      { i: '1', x: 0, y: 0, w: 2, h: 2 },
      { i: '2', x: 0, y: 0, w: 2, h: 2 },
      { i: '3', x: 0, y: 0, w: 2, h: 2 },
      { i: '4', x: 0, y: 0, w: 2, h: 2 },
      { i: '5', x: 0, y: 0, w: 4, h: 2 },
    ],
    sm: [
      { i: '1', x: 0, y: 0, w: 2, h: 2 },
      { i: '2', x: 0, y: 0, w: 2, h: 2 },
      { i: '3', x: 0, y: 0, w: 2, h: 2 },
      { i: '4', x: 0, y: 0, w: 2, h: 2 },
      { i: '5', x: 0, y: 0, w: 4, h: 2 },
    ],
  });

  // 网格项数据
  const gridItems: GridItemProps[] = [
    { i: '1', title: 'Item 1', color: '#4287f5' },
    { i: '2', title: 'Item 2', color: '#f5a642' },
    { i: '3', title: 'Item 3', color: '#42f579' },
    { i: '4', title: 'Item 4', color: '#f542a1' },
    { i: '5', title: 'Item 5', color: '#a142f5' },
  ];

  // 处理布局变化（拖拽后会触发）
  const handleLayoutChange = (currentLayout: Layout[], allLayouts: Layouts) => {
    // 更新布局状态
    setLayouts(allLayouts);
  };

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <h2 className="text-2xl font-bold mb-6 text-center">可拖拽的网格布局</h2>
      <p className="text-center mb-6 text-gray-600">
        拖动项目可以改变它们的位置，尝试一下！
      </p>

      <ResponsiveGridLayout
        layouts={layouts}
        breakpoints={{ lg: 1200, md: 996, sm: 768 }}
        cols={{ lg: 6, md: 6, sm: 6 }}
        rowHeight={120}
        margin={[15, 15]}
        // 启用拖拽功能（默认就是true，但显式设置更清晰）
        isDraggable={true}
        // 可以禁用调整大小（只保留拖拽功能）
        isResizable={false}
        // 拖拽时的回调

        // 拖拽结束的回调

        // 布局变化的回调
        onLayoutChange={handleLayoutChange}
        className="bg-gray-100 p-4 rounded-lg"
      >
        {gridItems.map((item) => (
          <div
            key={item.i}
            style={{
              backgroundColor: item.color,
              color: 'white',
              padding: '16px',
              borderRadius: '8px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
            }}
          >
            <h3 className="font-bold text-lg">{item.title}</h3>
            <p>可以拖拽我移动位置</p>
          </div>
        ))}
      </ResponsiveGridLayout>
    </div>
  );
};

export default DraggableGrid;
